<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "   prop="departmentId">
          <el-select v-model="listQuery.departmentId" @change="deptChange" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="停车场">
          <el-select v-model="listQuery.parkId" placeholder="请选择" clearable style="width: 90px;">
            <el-option
              v-for="item in allParkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label=" 出入口名称">
          <el-input v-model="listQuery.name" clearable class="filter-item" style="max-width: 260px;" placeholder="出入口名称"/>
        </el-form-item>

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

        <el-button
          v-hasPermi="['admin:parkPort:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >
      <!-- <el-table-column align="center" label="出入口id" prop="id" /> -->

      <el-table-column align="center" label="所属机构" prop="departmentName"/>
      <el-table-column align="center" label="停车场" prop="parkName"/>
      <el-table-column align="center" label="通道名称" prop="passwayName"/>
      <el-table-column align="center" label="出入口名称" prop="name" />

      <el-table-column align="center" label="类型" prop="type">
        <template slot-scope="scope">
          <el-tag >{{ getType(scope.row.type) }}</el-tag>
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" label="设备IP" prop="railIp"/> -->
      <!-- <el-table-column align="center" label="道闸标识" prop="railId"/>
      <el-table-column align="center" label="道闸编码" prop="railCode"/>
      <el-table-column align="center" label="道闸类型" prop="railTypeStr"/> -->

      <!-- <el-table-column align="center" label="二维码" prop="status">
        <template slot-scope="scope">
          <el-button v-if="scope.row.railUrl && scope.row.railUrl.length > 0" type="primary" style="margin-left: 20px" @click="qrCode(scope.row.id)">缴费二维码</el-button>
        </template>
      </el-table-column> -->

      <!-- <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag >{{ getStatus(scope.row.status) }}</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="left" label="操作" width="400" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            v-hasPermi="['admin:parkPort:update']"
            type="primary"
            size="small"
            @click="startEditPassway(row)">编辑</el-button>
          <!-- <el-button type="primary" size="small" @click="deletePassway(scope.row.name, scope.row.id)">删除</el-button> -->
          <el-button type="primary" size="small" @click="qrCode(row)">缴费码</el-button>
          <el-button type="primary" v-if="row.tempLicenseQrcode" size="small" @click="lsqrCode(row)">临时车牌码</el-button>
          <!-- <el-button
            v-hasPermi="['admin:parkPort:railInit']"
            type="primary"
            size="small"
            @click="handleInitRail(scope.row)">初始化</el-button> -->
          <el-button
            v-hasPermi="['admin:parkPort:railOpen']"
            type="primary"
            size="small"
            @click="openingGate(row)">开闸</el-button>
            <!-- <el-button v-if="scope.row.railUrl && scope.row.railUrl.length > 0" type="primary" size="small" @click="doOpenRail(scope.row.id)">无车开闸</el-button>
          <el-button v-if="scope.row.railUrl && scope.row.railUrl.length > 0" type="primary" size="small" @click="startOpenRail(scope.row.id)">有车开闸</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogFormVisible" width="48%">
      <el-form ref="dialogForm" :inline="dialogTitle == '开闸' ? false : true" :rules="dialogTitle == '开闸' ? formRules1 : formRules " :model="dialogForm"  label-width="140px">
        <div v-if="dialogTitle == '开闸'">
          <el-form-item label=" 车牌号码  " prop="plateNumber">
            <el-input v-model="dialogForm.plateNumber" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
          </el-form-item>
          <el-form-item label=" 类型  " prop="feeType" v-if="dialogForm.crType !== 1">
            <el-select v-model="dialogForm.feeType"  placeholder="请选择">
              <el-option
                v-for="item in dict.type.EManualRailFeeType"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)"/>
            </el-select>
          </el-form-item>
          <el-form-item label=" 截图  " >
            <el-image
              style="width: 200px; height: 200px;cursor: pointer;"
              :src="dialogForm.printScreenImg"
              :preview-src-list="[dialogForm.printScreenImg]"
              >
            </el-image>
          </el-form-item>

          <el-form-item label=" 备注  " prop="remark">
            <el-input :rows="6" v-model="dialogForm.remark" type="textarea" clearable class="filter-item"  placeholder=""/>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label=" 机构  " prop="departmentId">
            <el-select :disabled="dialogType != 1" v-model="dialogForm.departmentId"  placeholder="请选择" @change="jigouChange">
              <el-option
                v-for="item in departmentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label=" 停车场  " prop="parkId">
            <el-select :disabled="dialogType != 1" v-model="dialogForm.parkId" placeholder="请选择" @change="tingcheChange">
              <el-option
                v-for="item in parkList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>

          <el-form-item label=" 通道  " prop="passwayId">
            <el-select  v-model="dialogForm.passwayId"  placeholder="请选择">
              <el-option
                v-for="item in passwayList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label=" 出入口类型  " prop="type">
            <el-select :disabled="dialogType != 1" v-model="dialogForm.type" placeholder="请选择" >
              <el-option
                v-for="item in type_options"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>

          <el-form-item label=" 出入口名称  " prop="name">
            <el-input v-model="dialogForm.name" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
          </el-form-item>
          <!-- <el-form-item label=" 道闸ip  " prop="railIp">
            <el-input v-model="dialogForm.railIp" clearable onkeyup="value=value.replace(/[^\d\.]/g,'')" class="filter-item" style="max-width: 260px;" placeholder=""/>
          </el-form-item> -->
          <!-- <el-form-item label="道闸标识" prop="railId">
            <el-input v-model="dialogForm.railId" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
          </el-form-item>
          <el-form-item label="道闸编码" prop="railCode">
            <el-input v-model="dialogForm.railCode" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
          </el-form-item>
          <el-form-item label="道闸类型" prop="railType">
            <el-radio-group v-model="dialogForm.railType">
              <el-radio :label="1">海康</el-radio>
              <el-radio :label="2">臻识</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item label="备注">
            <el-input v-model="dialogForm.remark" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
          </el-form-item>
          <el-form-item label=" 是否开启音量控制  " prop="volControlFlag">
            <el-select v-model="dialogForm.volControlFlag" placeholder="请选择" >
              <el-option
                v-for="item in yinliangList"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-row v-if="dialogForm.volControlFlag == 1">
            <el-col :span="24">
              <div
              v-for="(item,index) in dialogForm.parkPortVols" :key="index">
                <el-form-item label=" 音量控制  " prop="">
                  <div class="flex_hcneter">
                    <el-select v-model="item.type" placeholder="请选择" >
                      <el-option
                        v-for="item in ylList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"/>
                    </el-select>
                    <el-button
                    @click="addYl"
                    style="margin-left: 15px;" type="primary">+</el-button>
                    <el-button @click="delyl(index)" v-if="dialogForm.parkPortVols.length > 1"
                    style="margin-left: 15px;" type="primary">-</el-button>
                  </div>
                </el-form-item>
                <el-form-item :label=" '时间段' + (index+1)  " prop="" v-if="item.type == 2">
                  <div class="flex_hcneter">
                    <el-time-select
                      v-model="item.startTime"
                      :picker-options="{
                        start: '00:00',
                        step: '00:01',
                        end: '24:00'
                      }"
                      placeholder="选择时间">
                    </el-time-select>
                    <div style="margin: 0px 10px;">-</div>
                    <el-time-select
                      v-model="item.endTime"
                      :picker-options="{
                        start: '00:00',
                        step: '00:01',
                        end: '24:00'
                      }"
                      placeholder="选择时间">
                    </el-time-select>
                  </div>
                </el-form-item>
                <div class="flex_hcneter" style="padding-left: 140px;">
                  <img style="width: 30px;height: 30px;margin-right: 10px;" src="@/assets/images/yinyue.png"/>
                  <el-slider style="flex:1;" v-model="item.vol"></el-slider>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="qrcodeDialogVisible" title="支付" width="20%">

      <div id="qrcode"/>
      <div class="flex_zhcenter" style="margin-top: 15px;font-size: 26px;">
        {{qrCodeTitle}}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="qrcodeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="qrcodeDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="manualDialogVisible" title="手动开闸" width="20%">

      <el-form ref="dialogForm" :inline="true" align="center" label-width="120px">
        <el-form-item label=" 车牌号码：  " prop="name">
          <el-input v-model="manualPlateNumber" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="manualDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doOpenRail(manualPortId, manualPlateNumber); manualDialogVisible = false">确 定</el-button>
      </span>

    </el-dialog>

  </div>
</template>

<script>
import { fetchList, deleteParkPort, createParkPort, updateParkPort, openRail, parkPortRailOpen,parkPortDetail,
 openGate,printScreen,railPlateNumber,} from '@/api/parkPort'
import { selectList,listAuthPassway,crlistAuthPort } from '@/api/passway'
import { getDepartmentList, initRail,getListAuthPark } from '@/api/base'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import QRCode from 'qrcodejs2'

export default {
  name: 'ParkPort',
  components: { Pagination },
	dicts: ['EManualRailFeeType'],
  data() {
    return {
      ylList:[//音量控制
        {value: 1,label: '全天音量'},
        {value: 2,label: '分段音量'},
      ],
      yinliangList:[//是否开启音量控制
        {value: 1,label: '是'},
        {value: 0,label: '否'},
      ],
      list: null,
      total: 0,
      listLoading: true,
      type_options: [{
        value: 1,
        label: '入口'
      }, {
        value: 2,
        label: '出口'
      }],
      listQuery: {
        page: 1,
        pageSize: 20
      },

      downloadLoading: false,
      dialogTitle: '温馨提示',
      dialogFormVisible: false,
      dialogForm: {},
      dialogType: 1,
      name: '',
      departmentList: [],
      parkList: [],
      allParkList: [],
      passwayList: [],
      qrcodeDialogVisible: false,
      manualPortId: 0,
      manualDialogVisible: false,
      manualPlateNumber: '',
      formRules1:{
        plateNumber: [{ required: true, message: '请输入车牌号码', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', validator: this.checkSelected, trigger: 'change' }],
      },
      formRules: {
        parkId: [{ required: true, message: '请选择停车场', validator: this.checkSelected, trigger: 'change' }],
        passwayId: [{ required: true, message: '请选择通道', validator: this.checkSelected, trigger: 'change' }],
        feeType: [{ required: true, message: '请选择出入口类型', validator: this.checkSelected, trigger: 'change' }],
        // railIp: [{ required: true, message: '请输入设备IP', validator: this.checkIP, trigger: 'blur' }],
        railId: [{ required: true, message: '请输入必填项', trigger: 'blur' }],
        railType: [{ required: true, message: '请输入必填项', trigger: 'blur' }],
        railCode: [{ required: true, message: '请输入必填项', trigger: 'blur' }],
        name: [{ required: true, message: '请输入出入口名称', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择机构名称', validator: this.checkSelected, trigger: 'change' }],
        volControlFlag: [{ required: true, message: '请选择是否开启音量控制', trigger: 'blur' }],
      },
      kazha: false,// 开闸请求冒泡
      ylObj:{
        type:1,
        startTime:'',endTime:'',vol:0,
      },
      qrCodeTitle:'',//码标题
    }
  },
  created() {
    this.getDepartmentList()
    this.getList()
  },
  methods: {
    getDepartmentList(){//获取机构
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
    async getListAuthPark(departmentId){//获取停车场
      let res = await getListAuthPark({departmentId,parkType:1})
      return res.data || []
    },
    addYl(){//添加配置
      this.dialogForm.parkPortVols.push({...this.ylObj})
    },
    delyl(index){
      this.dialogForm.parkPortVols.splice(index,1)
    },
    async deptChange(e){//机构下拉选择
      let listQuery = {...this.listQuery}
      listQuery.parkId = ''
      this.listQuery = {...listQuery}
      if(!e) return this.allParkList = []
      this.allParkList = await this.getListAuthPark(e)
    },
    async openingGate(row) { // 开闸
      this.dialogForm = {}
      this.dialogFormVisible = true
      this.dialogTitle = '开闸'
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
      let dialogForm = {...this.dialogForm}
      let res1 = await railPlateNumber(row.id)
      let data1 = res1.data || ''
      dialogForm.portId = row.id
      dialogForm.crType = row.type
      dialogForm.plateNumber = data1
      this.dialogForm = {...dialogForm}
      this.printScreen()

    },
    async printScreen(){//获取抓拍截图
      let res = await printScreen(this.dialogForm.portId)
      let data = res.data || ''
      let dialogForm = {...this.dialogForm}
      dialogForm.printScreenImg = data
      this.dialogForm = {...dialogForm}
    },
    handleInitRail(row) {
      this.$confirm(`您确定初始化出入口：${row.name}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        initRail({ portId: row.id })
      })

    },
    // 校验下拉框
    checkSelected(rule, value, callback) {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },
    // 校验IP地址
    checkIP(rule, value, callback) {
      var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      var valid = reg.test(value)
      if (!value) {
        callback(new Error(rule.message))
      } else if (!valid) {
        callback(new Error('请输入正确的IP地址'))
      } else {
        callback()
      }
    },

    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data = response.data || {}
        this.list = data.list || []
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getType(type) {
      if (type === 1) {
        return '入口'
      }
      return '出口'
    },
    getStatus(status) {
      if (status === 1) {
        return '启用'
      }
      return '停用'
    },
    deletePassway(name, parkId) {
      this.$confirm(`您确定删除出入口：${name}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteParkPort({ id: parkId }).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    doOpenRail(portId, plateNumber) {
      const openData = { 'id': portId }
      if (plateNumber) {
        openData['plateNumber'] = plateNumber
      }
      openRail(openData).then(response => {
        if (response.resultCode) {
          this.$message({
            message: '开闸执行完毕!',
            type: 'success'
          })
        }
      })
    },
    startOpenRail(portId) {
      this.manualPortId = portId
      this.manualDialogVisible = true
    },
    startAdd() {
      this.dialogForm = {parkPortVols:[{...this.ylObj}]}
      this.dialogFormVisible = true
      this.dialogType = 1
      this.dialogTitle = '添加出入口'
      this.parkList = []
      this.passwayList = []
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
      this.getDepartmentList()
    },
    confirmEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogTitle == '开闸') {
            openGate(this.dialogForm).then(response => {
              this.$message({
                message: '操作成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          } else {
            if(this.dialogForm.volControlFlag == 1){
              let parkPortVols = this.dialogForm.parkPortVols || []
              let flag = parkPortVols.filter(item=>item.type == 1)
              if(flag.length && parkPortVols.length > 1) return his.$message({
                    message: '您已设置全天音量无法创建其他!',
                    type: 'warning'
                  })
            }
            let dialogForm = {...this.dialogForm}
            if(dialogForm.volControlFlag != 1) delete dialogForm.parkPortVols
            if(this.dialogForm)
            if (this.dialogType === 1) {
              createParkPort(dialogForm).then(response => {
                this.$message({
                  message: '添加成功!',
                  type: 'success'
                })
                this.getList()
                this.dialogFormVisible = false
                this.dialogForm = {}
              })
            } else {
              updateParkPort(dialogForm).then(response => {
                this.$message({
                  message: '修改成功!',
                  type: 'success'
                })
                this.getList()
                this.dialogFormVisible = false
                this.dialogForm = {}
              })
            }
          }

        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async startEditPassway(row) {
      parkPortDetail(row.id).then(async response => {
        this.dialogFormVisible = true
        this.dialogTitle = '修改出入口'
        this.dialogType = 2
        let data = response.data || {}
        this.dialogForm = {...data,parkPortVols:data.parkPortVols || [{...this.ylObj}]}
        this.parkList = []
        await this.selectDepartmentId(row.departmentId)
        this.selectParkId(row.parkId)
        this.$nextTick(() => {
          this.$refs.dialogForm.clearValidate()
        })
        this.getDepartmentList()
      })

    },
    tingcheChange(e){//停车长改变
      this.passwayList = []
      let dialogForm = {...this.dialogForm}
      dialogForm.passwayId = ''
      this.dialogForm = {...dialogForm}
      this.selectParkId(e)
    },
    jigouChange(e){//机构选择改变
      let dialogForm = {...this.dialogForm}
      dialogForm.parkId = ''
      dialogForm.passwayId = ''
      this.dialogForm = {...dialogForm}
      this.selectDepartmentId(e)
    },
    async selectDepartmentId(event) {
      this.parkList = []
      this.parkList = await this.getListAuthPark(event)
    },
    selectParkId(event) {

      var getPassways = { 'parkId': event, 'page': 1 }
      listAuthPassway(event).then(response => {
        this.passwayList = response.data || []
      })
    },
    lsqrCode(row){//临时车牌二维码
      this.qrcodeDialogVisible = true
      this.qrCodeTitle = '临时车牌登记二维码'
      this.$nextTick(function() {
        document.getElementById('qrcode').innerHTML = ''
        new QRCode('qrcode', {
          width: 250,
          height: 250,
          text: row.tempLicenseQrcode,
          colorDark: '#ffffff',
          colorLight: '#000000',
          correctLevel: QRCode.CorrectLevel.H
        })
      })
    },
    qrCode(row) {
      this.qrcodeDialogVisible = true
      this.qrCodeTitle = '出入口缴费二维码'
      this.$nextTick(function() {
        document.getElementById('qrcode').innerHTML = ''
        new QRCode('qrcode', {
          width: 250,
          height: 250,
          text: row.qrcode,
          colorDark: '#ffffff',
          colorLight: '#000000',
          correctLevel: QRCode.CorrectLevel.H
        })
      })
    }

  }
}
</script>
<style scoped>
#qrcode{
  width: 250px;
  margin: 0 auto;
}
</style>
